package com.hunan.api.catv.service.biz.news;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.dto.AntiTheftChainConfig;
import com.hunan.api.catv.entity.dto.NewsDto;
import com.hunan.api.catv.entity.enums.ColumnEnum;
import com.hunan.api.catv.entity.enums.NewsState;
import com.hunan.api.catv.entity.enums.TpnsContentType;
import com.hunan.api.catv.entity.po.ActivationQrCode;
import com.hunan.api.catv.entity.po.MemberAttentionRecord;
import com.hunan.api.catv.entity.po.News;
import com.hunan.api.catv.entity.vo.ColumnVo;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.entity.vo.NewsVo;
import com.hunan.api.catv.entity.vo.SystemDictVo;
import com.hunan.api.catv.entity.vo.news.ListVo;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.column.ColumnBiz;
import com.hunan.api.catv.service.biz.comment.CommentBiz;
import com.hunan.api.catv.service.biz.like.MemberLikeBiz;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.mix.MixRecommendBiz;
import com.hunan.api.catv.service.biz.mq.MqBiz;
import com.hunan.api.catv.service.biz.system.SystemDictBiz;
import com.hunan.api.catv.service.biz.tag_content.TagContentBiz;
import com.hunan.api.catv.service.impl.news.NewsService;
import com.hunan.api.catv.service.impl.tencent_cloud.tms.TmsService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.PageUtils;
import com.hunan.api.catv.utils.RedisUtils;
import com.tencentcloudapi.tms.v20200713.models.TextModerationResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@CacheConfig(cacheNames = CacheName.news)
@Service
public class NewsBiz extends ResultService {

    @Autowired
    NewsService newsService;

    @Autowired
    NewsBiz newsBiz;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ColumnBiz columnBiz;

    @Autowired
    TagContentBiz tagItemBiz;

    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    MqBiz mqBiz;

    @Autowired
    TagContentBiz tagContentBiz;

    @Autowired
    SystemDictBiz systemDictBiz;

    @Autowired
    MixRecommendBiz mixRecommendBiz;

    @Autowired
    CommentBiz commentBiz;

    @Autowired
    MemberBiz memberBiz;

    @Value("${news.comment.counts}")
    private Integer newsCommentCounts;

    @Autowired
    MemberLikeBiz memberLikeBiz;

    @Autowired
    private TmsService tmsService;

    public ServiceResult add(News news) {
        SystemDictVo dic = systemDictBiz.getByKey(Constants.app_init_conf);
        JsonArray array = GsonUtils.fromJson(dic.getDictValue(), JsonArray.class);
        array.forEach(a -> {
            JsonObject o = GsonUtils.fromJson(GsonUtils.toJson(a), JsonObject.class);
            String type = o.get("type").getAsString();
            Integer start = o.get("start").getAsInt();
            Integer end = o.get("end").getAsInt();
            Integer count = ThreadLocalRandom.current().nextInt(start, end + 1);
            if ("up".equals(type)) {
                news.setBaseLike(count);
            }
            if ("play".equals(type)) {
                news.setBasePlay(count);
            }
        });
        ServiceResult result = newsService.add(news);
        if (result.getStatus()) {
            result = tagContentBiz.add(news.getTagIds(), news.getNewsId(), ColumnEnum.news.getCode(), news.getColumnId());
            if (result.getStatus()) {
                return buildOK(true, ConstantsMsg.admin_add_success);
            }
        }
        return buildFail(false, ConstantsMsg.admin_add_fail);
    }

    public ServiceResult update(News news) {
        ServiceResult result = newsService.update(news);
        if (result.getStatus()) {
            result = tagContentBiz.edit(news.getTagIds(), news.getNewsId(), ColumnEnum.news.getCode(), news.getColumnId());
            if (result.getStatus()) {
                String simpleInfoKey = MessageFormat.format(CacheName.newsSimpleInfo, String.valueOf(news.getNewsId()));
                cacheBiz.flushCacheInfo("newsInfoCache?" + news.getNewsId(), simpleInfoKey);
                mqBiz.push(MqConstants.news_exchange, MqConstants.news_routingkey, news.getNewsId());
            }
        }
        if (result.getStatus()) {
            return buildOK(true, ConstantsMsg.admin_edit_success);
        }
        return buildFail(false, ConstantsMsg.admin_edit_fail);
    }

    public ServiceResult update(Integer newsId, Integer state) {
        News news = new News();
        news.setNewsId(newsId);
        news.setState(state);
        ServiceResult serviceResult = newsService.update(news);
        if (serviceResult.getStatus()) {
            // 清除缓存
            String simpleInfoKey = MessageFormat.format(CacheName.newsSimpleInfo, String.valueOf(news.getNewsId()));
            cacheBiz.flushCacheInfo("newsInfoCache?" + newsId, simpleInfoKey);
            //同步solr
            mqBiz.push(MqConstants.news_exchange, MqConstants.news_routingkey, news.getNewsId());
        }
        return serviceResult;
    }

    public NewsVo simpleReplaceCache(Integer newsId) {
        return newsService.simpleInfo(newsId);
    }

    public PageInfo<NewsVo> adminList(int pageNum, int pageSize, Integer state, Integer columnId, String title) {
        PageHelper.startPage(pageNum, pageSize);
        News news = new News();
        news.setState(state);
        news.setColumnId(columnId);
        news.setTitle(title);
        List<NewsVo> list = newsService.list(news);
        for (int i = 0; i < list.size(); i++) {
            NewsVo newsVo = list.get(i);
            newsVo.setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));
            newsVo.setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
            ColumnVo columnVo = columnBiz.info(newsVo.getColumnId());
            if (!ObjectUtils.isEmpty(columnVo)) {
                newsVo.setColumn(columnVo);
            } else {
                newsVo.setColumn(new ColumnVo());
            }
            NewsState newsState = NewsState.getResult(newsVo.getState() == 4 ? 1 : newsVo.getState());
            newsVo.setStateMsg(newsState.getMsg());

        }
        return new PageInfo<NewsVo>(list);
    }

    public PageInfo<NewsVo> solrList(int pageNum, int pageSize, Integer state) {
        PageHelper.startPage(pageNum, pageSize);
        News news = new News();
        news.setState(state);
        List<NewsVo> list = newsService.list(news);
        for (int i = 0; i < list.size(); i++) {
            NewsVo newsVo = list.get(i);
            newsVo.setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));
            newsVo.setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
            ColumnVo columnVo = columnBiz.info(newsVo.getColumnId());
            if (!ObjectUtils.isEmpty(columnVo)) {
                newsVo.setColumn(columnVo);
            } else {
                newsVo.setColumn(new ColumnVo());
            }
            NewsState newsState = NewsState.getResult(newsVo.getState());
            newsVo.setStateMsg(newsState.getMsg());
        }
        return new PageInfo<NewsVo>(list);
    }

    public NewsVo info(Integer newsId) {
        NewsVo newsVo = newsService.getById(newsId);
        if (!ObjectUtils.isEmpty(newsVo)) {
            newsVo.setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));
            newsVo.setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
            String tagIds = tagContentBiz.getTagIds(newsId, ColumnEnum.news.getCode(), newsVo.getColumnId());
            newsVo.setTagIds(tagIds);
        }
        return newsVo;
    }

    @Cacheable(unless = "#result == null")
    public NewsVo simpleInfo(Integer newsId) {
        NewsVo newsVo = newsService.simpleInfo(newsId);
        if (!ObjectUtils.isEmpty(newsVo)) {
            newsVo.setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));
            newsVo.setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
            newsVo.setVideoProportion(StringUtils.isEmpty(newsVo.getVideoProportion()) ? "16:9" : newsVo.getVideoProportion());
            newsVo.setPositio(StringUtils.isEmpty(newsVo.getPositio()) ? "长沙" : newsVo.getPositio());
            String shareLinkdomain = cacheBiz.getSystemDict(Constants.shareLink_domain);
            newsVo.setShareLink(shareLinkdomain + "/h5?newsId=" + newsId);
        }
        return newsVo;
    }


    @Cacheable(unless = "#result == null")
    public PageInfo<NewsVo> newsList(Integer columnId, int pageNum, int pageSize) {
        PageInfo<Integer> idsPage = newsBiz.idsList(columnId, pageNum, pageSize);
        List<Integer> ids = idsPage.getList();
        List<NewsVo> newsVoList = new LinkedList<>();
        for (int i = 0; i < ids.size(); i++) {
            NewsVo newsVo = cacheBiz.newsInfo(ids.get(i));
            if (!ObjectUtils.isEmpty(newsVo)) {
                newsVoList.add(newsVo);
            }
        }
        PageInfo<NewsVo> pageInfo = new PageInfo<NewsVo>();
        BeanUtils.copyProperties(idsPage, pageInfo);
        pageInfo.setList(newsVoList);
        return pageInfo;
    }

    @Cacheable(unless = "#result == null")
    public PageInfo<Integer> idsList(Integer columnId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        News news = new News();
        news.setColumnId(columnId);
        List<Integer> list = newsService.listIds(news);
        return new PageInfo<>(list);
    }

    /**
     * 获取未置顶的短视频列表
     */
    @Cacheable(unless = "#result == null")
    public PageInfo<Integer> newsIdList(Integer columnId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Integer> list = newsService.newsIdList(columnId);
        return new PageInfo<>(list);
    }

    public NewsVo getById(Integer newsId) {
        return newsService.getById(newsId);
    }

    public ServiceResult play(Integer newsId) {
        redisUtils.hincr(CacheKey.playCount, String.valueOf(newsId), 1);
        mqBiz.push(MqConstants.news_play_exchange, MqConstants.news_play_routingkey, newsId);
        return buildOK(true);
    }

    public static String format(Integer count) {
        if (count < 10000) {
            return String.valueOf(count);
        }
        if (count % 10000 == 0) {
            return count / 10000 + "w";
        }
        double c = Double.valueOf(count + ".0");
        return String.format("%.1f", c / 10000) + "w";
    }


    public void incrCount(Integer newsId, Integer type) {
        News news = new News();
        news.setNewsId(newsId);
        if (type == 1) {
            news.setLikeNum(1);
        }
        if (type == 2) {
            news.setPlayNum(1);
        }
        Integer count = newsService.incrCount(news);
        if (count > 0) {
            //mqBiz.pushFANOUT(MqConstants.news_local_cache_exchange, newsId);
            //redisUtils.del(MessageFormat.format(CacheName.getNewsInfo,String.valueOf(newsId)));
            flushNewsCache(newsId);
            mixRecommendBiz.flushNewsCache(newsId);
        }
    }

    public void decrCount(Integer newsId, Integer type) {
        News news = new News();
        news.setNewsId(newsId);
        if (type == 1) {
            news.setLikeNum(1);
        }
        if (type == 2) {
            news.setPlayNum(1);
        }
        Integer count = newsService.decrCount(news);
        if (count > 0) {
            //mqBiz.pushFANOUT(MqConstants.news_local_cache_exchange, newsId);
            //redisUtils.del(MessageFormat.format(CacheName.getNewsInfo,String.valueOf(newsId)));
            flushNewsCache(newsId);
            mixRecommendBiz.flushNewsCache(newsId);
        }
    }


    public void flushNewsCache(Integer newsId) {
        String simpleInfoKey = MessageFormat.format(CacheName.newsSimpleInfo, String.valueOf(newsId));
        cacheBiz.flushCacheInfo("newsInfoCache?" + newsId, simpleInfoKey);
//        mqBiz.push(MqConstants.news_exchange, MqConstants.news_routingkey,newsId);
        NewsVo newsVo = newsBiz.getById(newsId);
        if (!ObjectUtils.isEmpty(newsVo)) {
            Integer total = newsService.totalNum(newsVo.getColumnId());
            Integer size = total / 20 + 1;
//			Integer pageNum = 1;
            List<NewsVo> newList = new ArrayList<NewsVo>();
            PageInfo<NewsVo> newPage = new PageInfo<NewsVo>();
            for (int i = 1; i <= size; i++) {
                PageInfo<NewsVo> page = newsBiz.newsList(newsVo.getColumnId(), i, 20);//cacheBiz.newsList(newsVo.getColumnId(), i, 20);
                List<NewsVo> list = page.getList();

                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getNewsId().equals(newsId)) {

                        list.get(j).setBaseLike(newsVo.getBaseLike());
                        list.get(j).setLikeNum(newsVo.getLikeNum());
                        list.get(j).setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));

                        list.get(j).setBasePlay(newsVo.getBasePlay());
                        list.get(j).setPlayNum(newsVo.getPlayNum());
                        list.get(j).setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
                        newList = list;
                        newPage = page;
                        newPage.setList(newList);
                        String key = newsVo.getColumnId() + "." + i + "." + 20;
                        String redisKey = "n::newsList." + key;
                        redisUtils.set(redisKey, newPage);
                        break;
                    }
                }

//				Iterator<NewsVo> it = list.iterator();
//				while(it.hasNext()) {
//					if(newsId.equals(it.next().getNewsId())) {
//						pageNum = i;
//						NewsVo newsVo2  = it.next();
//						newsVo2.setLikeNum(newsVo.getLikeNum());
//						newsVo2.setPlayNum(newsVo.getPlayNum());
//						break;
//					}
//				}
            }

//			@SuppressWarnings("unchecked")
//			LoadingCache<Object,PageInfo<NewsVo>> bean = SpringBeanUtils.getBean("newsListCache", LoadingCache.class);
            //bean.invalidate(key);
//			bean.put(key, newPage);
        }
    }

    /**
     * 优化短视频列表
     */
    public PageInfo<NewsVo> getNewsList(Integer columnId, int pageNum, Integer pageSize, Integer memberId) {
        if (columnId == -1) {
            return getNewsListByRecommend(columnId, pageNum, pageSize, memberId);
        }
        PageInfo<Integer> idsPage = newsBiz.newsIdList(columnId, pageNum, pageSize);
        List<NewsVo> newsVoList = getNewsInfoList(idsPage.getList(), memberId);
        PageInfo<NewsVo> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(idsPage, pageInfo);
        pageInfo.setList(newsVoList);
        return pageInfo;
    }

    public NewsVo getNewsInfo(Integer newsId) {
        String newsKey = MessageFormat.format(CacheName.getNewsInfo, String.valueOf(newsId));
        NewsVo newsVo = (NewsVo) redisUtils.get(newsKey);
        if (newsVo == null) {
            News news = new News().selectById(newsId);
            if (!ObjectUtils.isEmpty(news)) {
                newsVo = new NewsVo();
                BeanUtils.copyProperties(news, newsVo);
                newsVo.setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));
                newsVo.setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
                newsVo.setVideoProportion(StringUtils.isEmpty(newsVo.getVideoProportion()) ? "16:9" : newsVo.getVideoProportion());
                newsVo.setPositio(StringUtils.isEmpty(newsVo.getPositio()) ? "长沙" : newsVo.getPositio());
                String shareLinkdomain = cacheBiz.getSystemDict(Constants.shareLink_domain);
                newsVo.setShareLink(shareLinkdomain + "/h5?newsId=" + newsId);
                MemberVo info = memberBiz.info(newsVo.getMemberId());
                if (info != null) {
                    newsVo.setNickName(info.getNickName());
                    newsVo.setAvatarUrl(info.getAvatarUrl());
                }
                redisUtils.set(newsKey, newsVo);
            }
        }

        return newsVo;
    }

    /**
     * 查询状态正常的短视频信息
     */
    private List<NewsVo> getNewsInfoList(List<Integer> ids, Integer memberId) {
        List<NewsVo> newsVoList = new LinkedList<>();
        for (Integer newsId : ids) {
            NewsVo newsVo = getNewsInfo(newsId);
            if (newsVo.getState() != 1) {
                continue;
            }
            if (memberId != null) {
                //查询该用户是否点赞该视频
                newsVo.setLikeState(memberLikeBiz.itemLikeV2(TpnsContentType.news.getCode(), newsId, memberId));
            }
            if (!ObjectUtils.isEmpty(newsVo)) {
                //获取热评
                newsVo.setCommentVo(commentBiz.getHotCommentsByNewsId(newsId));
                newsVoList.add(newsVo);
            }
        }
        return newsVoList;
    }

    /**
     * 查询所有状态短视频信息
     */
    private List<NewsVo> getNewsInfoListByStatus(List<Integer> ids, Integer memberId) {
        List<NewsVo> newsVoList = new LinkedList<>();
        for (Integer newsId : ids) {
            NewsVo newsVo = getNewsInfo(newsId);
            if (memberId != null) {
                //查询该用户是否点赞该视频
                newsVo.setLikeState(memberLikeBiz.itemLikeV2(TpnsContentType.news.getCode(), newsId, memberId));
            }
            if (!ObjectUtils.isEmpty(newsVo)) {
                //获取热评
                newsVo.setCommentVo(commentBiz.getHotCommentsByNewsId(newsId));
                newsVoList.add(newsVo);
            }
        }
        return newsVoList;
    }

    /**
     * 推荐栏目下获取当天之前的短视频列表
     */
    private PageInfo<NewsVo> getNewsListByRecommend(Integer columnId, int pageNum, Integer pageSize, Integer memberId) {
        List<ListVo> lists = (List<ListVo>) redisUtils.get(CacheName.newsIdList);
        if (CollectionUtils.isEmpty(lists)) {
            return new PageInfo<>(new ArrayList<>());
        }
        //总页数
        int totalPages = lists.size() % pageSize != 0 ? (lists.size() / pageSize) + 1 : lists.size() / pageSize;
        Object pageNumByMember = redisUtils.hget(CacheName.memberPageByNews, String.valueOf(memberId));
        if (pageNumByMember == null) {
            pageNum = 1;
        } else {
            if ((int) pageNumByMember > totalPages) {
                pageNum = 1;
            } else {
                pageNum = (int) pageNumByMember;
            }
        }
        PageInfo<ListVo> listVoPageInfo = PageUtils.startPage(lists, pageNum, pageSize);
        List<NewsVo> newsVoList = getNewsInfoList(listVoPageInfo.getList().stream().map(ListVo::getNewsId).collect(Collectors.toList()), memberId);
        PageInfo<NewsVo> newsVoPageInfo = new PageInfo<>();
        BeanUtils.copyProperties(listVoPageInfo, newsVoPageInfo);
        newsVoPageInfo.setList(newsVoList);
        redisUtils.hset(CacheName.memberPageByNews, String.valueOf(memberId), pageNum + 1);
        return newsVoPageInfo;
    }


    /**
     * 根据位置标签获取短视频列表
     */
    public Object getNewsListByPosition(int pageNum, int pageSize, String positio, Integer memberId) {
        QueryWrapper<News> wrapper = new QueryWrapper<News>().select(News.NEWSID).eq(News.NEWSTYPE, 2).eq(News.DELETED, 1).eq(News.STATE, 1);
        List<Integer> newsIdList = new ArrayList<>();
        if (StringUtils.isEmpty(positio)) {
            newsIdList = new News().selectList(wrapper.eq(News.VIDEO_SOURCE, 0)).stream().map(News::getNewsId).collect(Collectors.toList());
        } else {
            newsIdList = new News().selectList(wrapper.like(News.POSITIO, positio)).stream().map(News::getNewsId).collect(Collectors.toList());
            //如果该位置下没有发版的短视频,默认为长沙
            if (CollectionUtils.isEmpty(newsIdList)) {
                positio = "长沙";
                newsIdList = new News().selectList(new QueryWrapper<News>().select(News.NEWSID).eq(News.NEWSTYPE, 2).eq(News.DELETED, 1).eq(News.STATE, 1).like(News.POSITIO, positio)).stream().map(News::getNewsId).collect(Collectors.toList());
            }
        }
        PageInfo<Integer> integerPageInfo = PageUtils.startPage(newsIdList, pageNum, pageSize);
        List<NewsVo> newsVoList = getNewsInfoList(integerPageInfo.getList(), memberId);
        Collections.shuffle(newsVoList);
        PageInfo<NewsVo> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(integerPageInfo, pageInfo);
        pageInfo.setList(newsVoList);
        return pageInfo;
    }

    /**
     * 获取个人发布短视频列表
     */
    public NewsDto getNewsListByMemberId(int pageNum, int pageSize, Integer memberId, Integer id) {
        MemberVo info = memberBiz.info(id);
        NewsDto newsDto = new NewsDto();
        if (info == null) {
            return newsDto;
        }
        //默认已关注
        Integer attentionState = 1;
        newsDto.setAvatarUrl(info.getAvatarUrl());
        String shareLink = cacheBiz.getSystemDict(Constants.share_person_page_link);
        newsDto.setSharePersonPageLink(shareLink + id);
        newsDto.setNickName(info.getNickName());
        QueryWrapper<News> wrapper = new QueryWrapper<News>().select(News.NEWSID).eq(News.MEMBER_ID, id).eq(News.DELETED, 1);
        if (!id.equals(memberId)) {
            wrapper.eq(News.STATE, 1);
            //判断是否关注
            MemberAttentionRecord memberAttentionRecord = new MemberAttentionRecord().selectOne(new QueryWrapper<MemberAttentionRecord>()
                    .eq(MemberAttentionRecord.MEMBER_ID, memberId)
                    .eq(MemberAttentionRecord.ATTENTION_ID, id)
                    .eq(MemberAttentionRecord.ATTENTION_TYPE, 0));
            if (memberAttentionRecord != null) {
                attentionState = memberAttentionRecord.getStatus();
            } else {
                attentionState = 0;
            }
        } else {
            wrapper.ne(News.STATE, 0);
        }
        newsDto.setAttentionState(attentionState);
        List<Integer> newsIdList = new News().selectList(wrapper.orderByDesc(News.CTIME)).stream().map(News::getNewsId).collect(Collectors.toList());
        PageInfo<Integer> integerPageInfo = PageUtils.startPage(newsIdList, pageNum, pageSize);
        List<NewsVo> newsVoList = getNewsInfoListByStatus(integerPageInfo.getList(), memberId);
        PageInfo<NewsVo> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(integerPageInfo, pageInfo);
        pageInfo.setList(newsVoList);
        newsDto.setList(pageInfo);
        return newsDto;
    }

    /**
     * 获取短视频置顶列表
     */
    public List<NewsVo> getNewsTopList(Integer column, Integer memberId) {
        //校验是否展示栏目置顶
        Boolean aBoolean = Boolean.valueOf(systemDictBiz.getStringByKey(Constants.top_switch_button));
        if (!aBoolean) {
            //如果查询栏目置顶不展示
            if (column != null && !"-1".equals(String.valueOf(column))) {
                return new ArrayList<>();
            }
        }
        //查询置顶的短视频
        QueryWrapper<News> wrapper = new QueryWrapper<News>().select(News.NEWSID)
                .eq(News.STATE, 1).eq(News.NEWSTYPE, 2).eq(News.DELETED, 1)
                .eq(News.TOP, 1);
        /*if("-1".equals(String.valueOf(column))){
            //推荐列表只查询当天之前的置顶列表
            Long dateTime = DateUtils.toLocalDateSecond(LocalDate.now());
            wrapper.lt(News.CTIME,dateTime);
        }else{
            wrapper.eq(News.COLUMNID, column);
        }*/
        if (!"-1".equals(String.valueOf(column))) {
            wrapper.eq(News.COLUMNID, column);
        }
        List<Integer> newsIdList = new News().selectList(wrapper.orderByDesc(News.CTIME))
                .stream().map(News::getNewsId).collect(Collectors.toList());
        return getNewsInfoList(newsIdList, memberId);
    }

    /**
     * 保存用户所发布的视频
     */
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult saveUserReleaseVideos(NewsVo newsVo, Integer memberId) {
        TextModerationResponse response = tmsService.textModeration(newsVo.getTitle().replaceAll("\\s", ""));
        String suggestion = response.getSuggestion();
        if ("Pass".equals(suggestion) || "Review".equals(suggestion)) {
            if ("Review".equals(suggestion)) {
                //标题疑似视频状态设为禁用
                newsVo.setState(0);
            } else {
                //上传视频默认状态为7需腾讯云审核
                newsVo.setState(7);
            }

            News news = new News();
            BeanUtils.copyProperties(newsVo, news);
            //用户发布视频来源ugc
            news.setVideoSource(1);
            news.setCTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
            news.setMemberId(memberId);
            news.setVideoProportion(StringUtils.isEmpty(newsVo.getVideoProportion()) ? "16:9" : newsVo.getVideoProportion());
            boolean insert = news.insert();
            if (insert) {
                //发布视频存入缓存
                NewsVo newsInfo = getNewsInfo(news.getNewsId());
                //視頻審核
                //mqBiz.push(MqConstants.RELEASE_VEDIO_EXCHANGE,MqConstants.RELEASE_VEDIO_ROUTINGKEY, GsonUtils.toJson(newsInfo));
                return buildOK(true, ConstantsMsg.admin_add_success);
            }
            return buildFail(ConstantsMsg.admin_add_fail);
        } else {
            return buildFail(ConstantsMsg.admin_add_fail_title);
        }
    }

    public News getNewsInfoByFileId(String fileId) {
        return newsService.getNewsInfoByFileId(fileId);
    }


    public NewsVo getNewsInfos(Integer newsId, Integer memberId) {
        NewsVo newsVo = this.getNewsInfo(newsId);
        if (memberId != null) {
            //查询该用户是否点赞该视频
            newsVo.setLikeState(memberLikeBiz.itemLikeV2(TpnsContentType.news.getCode(), newsId, memberId));
        }
        if (!ObjectUtils.isEmpty(newsVo)) {
            //获取热评
            newsVo.setCommentVo(commentBiz.getHotCommentsByNewsId(newsId));
        }
        return newsVo;
    }

    public Object specialNews(Integer memberId, String code) {
        JSONObject result = new JSONObject();
        Object o = redisUtils.hget("promise_my_story_film_activation", String.valueOf(memberId));
        if (ObjectUtils.isEmpty(o)) {
            ActivationQrCode activationQrCode = new ActivationQrCode().selectOne(new QueryWrapper<ActivationQrCode>().eq(ActivationQrCode.MEMBER_ID, memberId).eq(ActivationQrCode.STATE, 1).eq(ActivationQrCode.DELETED, 1));
            if (activationQrCode == null) {
                result.set("status", "0001");
                result.set("msg", "此用户未绑定激活码");
                return buildOK(result);
            }
        }
        JsonObject promiseMyStoryFilm = GsonUtils.fromJson(systemDictBiz.getStringByKey("promise_my_story_film"), JsonObject.class);
        if (!ObjectUtils.isEmpty(promiseMyStoryFilm)) {
            LocalDateTime now = LocalDateTime.now();
            String url = promiseMyStoryFilm.get("url").getAsString();
            String cover = promiseMyStoryFilm.get("cover").getAsString();
            String state = promiseMyStoryFilm.get("state").getAsString();
            String startTime = promiseMyStoryFilm.get("startTime").getAsString();
            String endTime = promiseMyStoryFilm.get("endTime").getAsString();
            int baseNum = promiseMyStoryFilm.get("num").getAsInt();

            if (!"1".equals(state)) {
                result.set("status", "0010");
                result.set("msg", "资源暂未开放");
                return buildOK(result);
            }
            if (!StringUtils.isEmpty(startTime) && LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).isAfter(now)) {
                result.set("status", "0011");
                result.set("msg", "电影暂未上映");
                return buildOK(result);
            }
            if (!StringUtils.isEmpty(endTime) && LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).isBefore((now))) {
                result.set("status", "0012");
                result.set("msg", "电影已下映");
                return buildOK(result);
            }

            int num = (int) Optional.ofNullable(redisUtils.get("promise_my_story_film_view_num")).orElse(0);
            promiseMyStoryFilm.addProperty("num", baseNum + num);
            AntiTheftChainConfig antiTheftChainConfig = JSONUtil.toBean(systemDictBiz.getStringByKey("AntiTheftChainConfig"), AntiTheftChainConfig.class);
            promiseMyStoryFilm.addProperty("url", antiTheftChainConfig.getAntiTheftUrl(url));
            return promiseMyStoryFilm;
        }
        return buildFail("获取视频信息失败");

    }

}
